// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

// Copyright (C) 2012	stfour

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gccore.h>
#include <unistd.h>
#include <fat.h>
#include <sys/stat.h> //for mkdir
#include <sdcard/wiisd_io.h>
#include <ogc/usbstorage.h>
#include "grlib/grlib.h"
#include "io.h"

extern char mex1[256];
extern char mex2[256];

const DISC_INTERFACE* interface[DEVMAX] = {NULL,NULL};
char mount[DEVMAX][16];

s32 Fat_Mount(int dev, int toutSec)
	{
	time_t t, ct, lt = 0;
	char m[5];

	ct = time(NULL);
	if (dev == DEV_SD)
		{
		interface[dev]=(DISC_INTERFACE*)&__io_wiisd;
		strcpy (m, "sd");
		t = ct + toutSec;
		}
	else if (dev == DEV_USB)
		{
		interface[dev]=(DISC_INTERFACE*)&__io_usbstorage;
		strcpy (m, "usb");
		t = ct + toutSec;
		}
	else
		return -1;

	printf ("Mounting %s device", m);

	while (t > ct)
		{
		ct = time(NULL);

		if (ct != lt)
			{
			if (interface[dev]->startup() &fatMountSimple(m, interface[dev]))
				{
				strcpy (mount[dev], m);
				return 1; // Mounted
				}
			lt = ct;
			}

		if (dev == DEV_SD) break;
		}

	interface[dev]->shutdown();

	printf ("\n");
	return 0;
	}

// Unmount all mounted devices
void Fat_Unmount(void)
	{
	int i;
	char mnt[64];

	for (i = 0; i < DEVMAX; i++)
		{
		if (mount[i][0] != '\0')
			{
			sprintf (mnt, "%s:/", mount[i]);
			fatUnmount(mnt);
			interface[i]->shutdown();
			mount[i][0] = '\0';
			}
		}
	}
